package com.lh.web.controller.order;

import com.lh.common.entity.admin.OrderAfterSaleAdmin;
import com.lh.common.entity.admin.OrderAfterSaleDetails;
import com.lh.common.entity.state.RemarkEnum;
import com.lh.common.enums.AfterStatusEnum;
import com.lh.common.enums.AfterTypeEnum;
import com.lh.common.enums.IF;
import com.lh.common.enums.OperTypeEnum;
import com.lh.common.utils.AssertUtil;
import com.lh.common.utils.Constant;
import com.lh.common.utils.PageUtils;
import com.lh.common.utils.Result;
import com.lh.web.config.OvmalConfig;
import com.lh.web.config.PayPalConfig;
import com.lh.web.controller.AbstractController;
import com.lh.web.form.RefundFrom;
import com.lh.web.form.ReturnGoodFrom;
import com.lh.web.service.serviceAdmin.order.AfterSalesOrderService;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.DetailedRefund;
import com.paypal.api.payments.RefundRequest;
import com.paypal.api.payments.Sale;
import com.paypal.base.rest.APIContext;
import com.razorpay.RazorpayClient;
import com.razorpay.RazorpayException;
import com.razorpay.Refund;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author FH
 * @ClassName: AfterSalesOrderAction
 * @Description: (售后订单管理)
 * @date: 2020-05-19 10:09
 */
@Api(value="AfterSalesOrderAction",tags={"售后订单管理"})
@RestController
@RequestMapping("afterSaleOrder")
public class AfterSalesOrderAction  extends AbstractController {

    @Autowired
    AfterSalesOrderService afterOrderService;

    @Autowired
    private OvmalConfig ovmalConfig;

    @Autowired
    PayPalConfig payPalConfig;

    /**
     * 查询售后订单页面
     */
    @ApiOperation(value = "查询售后订单页面")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "pageNum", value = "当前页", required = true,dataTypeClass= Integer.class),
            @ApiImplicitParam(paramType="query", name = "pageSize", value = "页数大小", required = true,dataTypeClass= Integer.class),
            @ApiImplicitParam(paramType="query", name = "orderItem", value = "订单编号", required = false, dataTypeClass= String.class),
            @ApiImplicitParam(paramType="query", name = "afterSaleId", value = "服务单号", required = false, dataTypeClass= String.class),
            @ApiImplicitParam(paramType="query", name = "afterSaleType", value = "服务类型", required = false, dataTypeClass= AfterTypeEnum.class),
            @ApiImplicitParam(paramType="query", name = "orderStatus", value = "订单状态", required = false, dataTypeClass= AfterStatusEnum.class),
            @ApiImplicitParam(paramType="query", name = "receiveRecipients", value = "联系人", required = false, dataTypeClass= String.class),
            @ApiImplicitParam(paramType="query", name = "receivePhone", value = "联系人手机号", required = false, dataTypeClass= String.class)
    })
    @GetMapping("/getAfterSaleOrderList")
    @RequiresPermissions("afterSaleOrder:getAfterSaleOrderList")
    public Result<OrderAfterSaleAdmin> getAfterSaleOrderList(String orderItem, String afterSaleId, AfterTypeEnum afterSaleType, AfterStatusEnum orderStatus, String receiveRecipients, String receivePhone, Integer pageNum, Integer pageSize) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orderItem", orderItem);
        params.put("afterSaleId", afterSaleId);
        if(afterSaleType != null) {
            params.put("afterSaleType", afterSaleType.getValue());
        }
        if(orderStatus != null) {
            params.put("orderStatus", orderStatus.getValue());
        }
        params.put("receiveRecipients", receiveRecipients);
        params.put("receivePhone", receivePhone);
        PageUtils pageUtils = afterOrderService.queryAfterSaleOrderList(params, pageNum, pageSize);
        return Result.ok(pageUtils);
    }

    @ApiOperation(value = "退款")
    @PostMapping("/refund")
    @RequiresPermissions("afterSaleOrder:refund")
    public Result refund(@RequestBody RefundFrom refundFrom)throws Exception {
        OrderAfterSaleAdmin orderAfterSale = afterOrderService.queryAfterSaleOrder(refundFrom.getAfterSaleId());
        String oldStatus,newStatus;
        oldStatus = orderAfterSale.getStatus().getValue();
        if(refundFrom.getRefundType().equals(AfterTypeEnum.REFUND)){
            newStatus = AfterStatusEnum.REFUNDSUCCESS.getValue();
            if(!AfterStatusEnum.PROCESSING.equals(orderAfterSale.getStatus())){
                return Result.error("订单状态不是处理中的状态!");
            }
        }else {
            newStatus = AfterStatusEnum.RETURNSUCCESS.getValue();
            if(!AfterStatusEnum.REFUNDING.equals(orderAfterSale.getStatus())){
                return Result.error("订单状态不是退货退款中的状态!");
            }
        }
        APIContext apiContext = new APIContext(payPalConfig.getClientId(), payPalConfig.getClientSecret(), payPalConfig.getMode());
        Sale sale = new Sale();
        sale.setId(refundFrom.getPayPaymentsId());
        Amount amount = new Amount();
        amount.setCurrency(payPalConfig.getCurrency());
        RefundRequest refund = new RefundRequest();
        refund.setAmount(amount);
        amount.setTotal(refundFrom.getRefundPrice());
        refund.setReason(refundFrom.getReason());
        DetailedRefund res = sale.refund(apiContext, refund);
        if(!res.getState().equals("completed")){
            return Result.error("退款失败!");
        }
        afterOrderService.updateAfterSaleOrder(refundFrom.getAfterSaleId(),getUserId(),oldStatus,newStatus, RemarkEnum.SHZT00);
        return Result.ok();
    }

    @ApiOperation(value = "退货与入库操作")
    @PostMapping("/returnGoods")
    @RequiresPermissions("afterSaleOrder:returnGoods")
    public Result returnGoods(@RequestBody ReturnGoodFrom returnGoodFrom){
        String afterSaleId = returnGoodFrom.getAfterSaleId();
        OrderAfterSaleAdmin orderAfterSale = afterOrderService.queryAfterSaleOrder(returnGoodFrom.getAfterSaleId());
        String status = orderAfterSale.getStatus().getValue();
        if(returnGoodFrom.getType().equals(OperTypeEnum.RETURNGOODS)){
            if(!AfterStatusEnum.RETURNING.equals(orderAfterSale.getStatus())){
                return Result.error("订单状态不是退货处理中的状态!");
            }
            if(returnGoodFrom.getOperationType().equals(IF.YES)){
                afterOrderService.updateOperAfterSaleOrder(afterSaleId,getUserId(),returnGoodFrom.getAddrId(),returnGoodFrom.getRefuseId(),status,AfterStatusEnum.TOWAREHOUSE.getValue(),RemarkEnum.SHZT02);
            }else if(returnGoodFrom.getOperationType().equals(IF.NO)){
                afterOrderService.updateOperAfterSaleOrder(afterSaleId,getUserId(),returnGoodFrom.getAddrId(),returnGoodFrom.getRefuseId(),status,AfterStatusEnum.REFUSERETURN.getValue(),RemarkEnum.SHZT03);
            }
        }else {
            if(!AfterStatusEnum.TOWAREHOUSE.equals(orderAfterSale.getStatus())){
                return Result.error("订单状态不是退货入库中的状态!");
            }
            if(returnGoodFrom.getOperationType().equals(IF.YES)){
                afterOrderService.updateAfterSaleOrder(afterSaleId,getUserId(),status,AfterStatusEnum.REFUNDING.getValue(), RemarkEnum.SHZT19);
            }else if(returnGoodFrom.getOperationType().equals(IF.NO)){
                afterOrderService.updateOperAfterSaleOrder(afterSaleId,getUserId(),returnGoodFrom.getAddrId(),returnGoodFrom.getRefuseId(),status,AfterStatusEnum.REFUSEWAREHOUSE.getValue(),RemarkEnum.SHZT20);
            }
        }
        return Result.ok();
    }

    @ApiOperation(value = "拒绝退款")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "afterSaleId", value = "服务单号", required = true, dataTypeClass= String.class),
            @ApiImplicitParam(paramType="query", name = "refuseId", value = "退款拒绝原因", required = true, dataTypeClass= long.class)
    })
    @GetMapping("/refusalRefund")
    @RequiresPermissions("afterSaleOrder:refusalRefund")
    public Result refusalRefund(String afterSaleId,Long refuseId)throws RazorpayException {
        AssertUtil.assertNotNull(afterSaleId, Constant.RESULT.FI1000, "服务单号 不允许为空");
        OrderAfterSaleAdmin orderAfterSale = afterOrderService.queryAfterSaleOrder(afterSaleId);
        if(!(AfterStatusEnum.REFUNDING.equals(orderAfterSale.getStatus())||AfterStatusEnum.PROCESSING.equals(orderAfterSale.getStatus()))){
            return Result.error("订单状态不是退款处理中的状态!");
        }
        afterOrderService.updateOperAfterSaleOrder(afterSaleId,getUserId(),null,refuseId,orderAfterSale.getStatus().getValue(),AfterStatusEnum.REFUSEREFUND.getValue(),RemarkEnum.SHZT01);
        return Result.ok();
    }

    /**
     * 售后详情页面
     */
    @ApiOperation(value = "售后详情页面")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "afterSaleId", value = "服务单号", required = true, dataTypeClass= String.class)
    })
    @GetMapping("/getAfterSalesDetails")
    @RequiresPermissions("afterSaleOrder:getAfterSalesDetails")
    public Result<OrderAfterSaleDetails> getOrderAfterSalesDetails(String afterSaleId){
        OrderAfterSaleDetails orderAfterSaleDetails = afterOrderService.queryAfterSalesDetails(afterSaleId);
        return Result.ok(orderAfterSaleDetails);
    }
}
